package com.example.speeddating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.speeddating.entity.Follow;
import com.example.speeddating.entity.User;
import com.example.speeddating.enums.ResponseCodeEnum;
import com.example.speeddating.exception.CommonException;
import com.example.speeddating.mapper.FollowMapper;
import com.example.speeddating.mapper.UserMapper;
import com.example.speeddating.service.FollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author tina
 * @since 2023-06-28 11:14:33
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements FollowService {

    @Autowired
    private FollowMapper followMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public int batchupdateFollow(Long userId) {
        return followMapper.updateFollow(userId);
    }

    @Override
    public Page<User> selectFollowUser(Integer pageNum, Integer pageSize, Long userId) {
        Page<User> page = new Page<>(pageNum,pageSize);
        Page<User> userPage = followMapper.selectFollowUser(page, userId);
        for (User u : userPage.getRecords()) {
            Integer focus = userMapper.selectIsFocus(userId, u.getId());
            if (focus!=0){
                u.setIsFollowed(true);
            }else {
                u.setIsFollowed(false);
            }
        }
        return userPage;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUnreadFollow(Long id) {
        followMapper.updateFollowUser(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int followUser(Long userId, Long followId) {
        if (userId.equals(followId)){
            throw new CommonException("不能关注自己哦");
        }
        QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("follow_id",followId);
        Follow follow = followMapper.selectOne(queryWrapper);
        if (follow==null){
            Follow f = new Follow();
            f.setUserId(userId);
            f.setFollowId(followId);
            return followMapper.insertFollow(f);
        }else {
            throw new CommonException(ResponseCodeEnum.CODE_601);
        }
    }
}
